package middle

import (
	"encoding/json"
	"fmt"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/bson/primitive"
	"io"
	"net/http"
	"strings"
)

// GetAccountByNetWork 获取账号信息
func GetAccountByNetWork() (map[string][]string, error) {
	// 调用接口重新生成账号信息
	request, err := http.NewRequest(http.MethodGet, "https://cmkf.cmcc-cs.cn/portal/xiaohe/authCode/api/getAll", nil)
	if err != nil {
		return nil, fmt.Errorf("获取autcode，创建请求失败: %v", err)
	}
	// 设置请求头
	request.Header.Set("Accept", "application/json")
	request.Header.Set("accessKeyId", "56853a9f-c4be-405e-ba22-debbd3ae33c0")

	// 发送请求
	response, err := http.DefaultClient.Do(request)
	if err != nil {
		return nil, fmt.Errorf("获取autcode，请求失败: %v", err)
	}
	defer response.Body.Close()

	if response.StatusCode != http.StatusOK {
		return nil, fmt.Errorf("获取autcode，请求失败,响应状态码：" + response.Status)
	}

	body, err := io.ReadAll(response.Body)
	if err != nil {
		return nil, fmt.Errorf("获取autcode，读取响应失败: %v", err)
	}
	type authcodeData struct {
		AreaCode     string `json:"areaCode"`
		PhoneNumber  string `json:"phoneNumber"`
		ProvinceCode string `json:"provinceCode"`
		Location     string `json:"location"`
		Ttl          string `json:"ttl"`
	}
	type authcodeResponse struct {
		RtnCode  string                  `json:"rtnCode"`
		RtnMsg   string                  `json:"rtnMsg"`
		Total    interface{}             `json:"total"`
		Object   map[string]authcodeData `json:"object"`
		Ok       bool                    `json:"ok"`
		RespCode string                  `json:"respCode"`
		ExpMsg   string                  `json:"expMsg"`
	}

	var result authcodeResponse
	err = json.Unmarshal(body, &result)
	if err != nil || result.RtnCode != "0" || result.Object == nil {
		return nil, fmt.Errorf("获取autcode，解析响应失败: %v", err)
	}

	// 清除旧数据
	account := make(map[string][]string)

	for authcode, phoneItem := range result.Object {
		accountInfo := fmt.Sprintf("%s|%s|%s", authcode, phoneItem.PhoneNumber, phoneItem.Location)
		if _, ok := account[phoneItem.ProvinceCode]; !ok {
			account[phoneItem.ProvinceCode] = []string{accountInfo}
		} else {
			account[phoneItem.ProvinceCode] = append(account[phoneItem.ProvinceCode], accountInfo)
		}
	}

	return account, nil
}

func GetWorkflowInfo() (map[string][]string, error) {
	// 聚合查询语句
	pipeline := []bson.M{
		// Step 1: 筛选 resource_version_record 基础条件
		{
			"$match": bson.M{
				"status":    2,
				"kind_code": "SKILL_PROCESS",
				"body_id":   bson.M{"$exists": true, "$ne": ""},
			},
		},

		// Step 2: 投影裁剪，只保留需要字段（减少内存）
		{
			"$project": bson.M{
				"_id":      1,
				"body_id":  1,
				"version":  1,
				"start_id": bson.M{"$arrayElemAt": []interface{}{"$data.topology.nodeList.id", 0}},
				"name":     1,
			},
		},

		// Step 3: 按 body_id 排序（升序），version 降序 → 为 group 做准备
		{
			"$sort": bson.M{
				"body_id": 1,
				"version": -1,
			},
		},

		// Step 4: 分组取每个 body_id 下第一条（即 version 最大）
		{
			"$group": bson.M{
				"_id":         "$body_id",
				"_id_version": bson.M{"$first": "$_id"},
				"version":     bson.M{"$first": "$version"},
				"_name":       bson.M{"$first": "$name"},
				"_start_id":   bson.M{"$first": "$start_id"},
			},
		},

		// Step 5: 恢复成原始文档结构
		{
			"$replaceRoot": bson.M{
				"newRoot": bson.M{
					"version_id": "$_id_version",
					"body_id":    "$_id",
					"name":       "$_name",
					"start_id":   "$_start_id",
				},
			},
		},

		// Step 6: 联表查询 intention_workflow_relation，返回所有匹配项
		{
			"$lookup": bson.M{
				"from": "intention_workflow_relation",
				"let":  bson.M{"body_id": "$body_id"},
				"pipeline": []bson.M{
					{
						"$match": bson.M{
							"$expr": bson.M{
								"$and": []bson.M{
									{"$eq": []string{"$body_id", "$$body_id"}},
									{"$eq": []interface{}{"$status", "2"}},
								},
							},
						},
					},
					{
						"$project": bson.M{
							"intent_name": 1,
							"app_id":      1,
							"app_secret":  1,
							"start_id":    1,
							"_id":         0,
						},
					},
				},
				"as": "workflows",
			},
		},

		// Step 7: 最终字段控制
		{
			"$project": bson.M{
				"_id":        0,
				"body_id":    1,
				"version_id": 1,
				"start_id":   1,
				"name":       1,
				"workflows":  1,
			},
		},
	}

	mongo, err := NewMongo("mongodb://172.31.184.115:30006", "root", "Mgadmin_1234")
	if err != nil {
		return nil, err
	}
	defer mongo.Close()

	resultList, err := mongo.AggregateSelect("flames_platform", "resource_version_record", pipeline...)
	if err != nil {
		return nil, err
	}

	canvasMap := make(map[string][]string)
	for _, result := range resultList {
		// 获取字段
		bodyId, _ := result["body_id"].(string)
		startId, _ := result["start_id"].(string)
		versionId, _ := result["version_id"].(string)
		name, _ := result["name"].(string)
		workflows, _ := result["workflows"].(primitive.A)

		// 未发版
		if len(workflows) == 0 {
			if name == "" {
				continue
			}
			canvasMap[strings.Split(name, "_v")[0]] = []string{
				"", "", bodyId, startId, versionId,
			}
			continue
		}
		// 已发版
		for _, item := range workflows {
			workflow, _ := item.(primitive.M)
			intentName, _ := workflow["intent_name"].(string)
			appId, _ := workflow["app_id"].(string)
			appSecret, _ := workflow["app_secret"].(string)
			startId, _ = workflow["start_id"].(string)
			if intentName == "" {
				continue
			}
			canvasMap[intentName] = []string{
				appId, appSecret, bodyId, startId, versionId,
			}
		}
	}
	return canvasMap, nil
}
